#include <errno.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char buf[1024];
sem_t sem[2];

void *func(void *);

int main(int argc, char *argv[]) {
  int ret;
  ret = sem_init(sem, 0, 1);
  if (ret != 0) {
    perror("sem_init fail");
    exit(-1);
  }
  ret = sem_init(sem + 1, 1, 0);
  if (ret != 0) {
    perror("sem_init fail");
    exit(-1);
  }
  pthread_t tid;
  ret = pthread_create(&tid, NULL, func, NULL);
  if (ret != 0) {
    perror("pthread_create fail");
    exit(-1);
  }
  while (1) {
    sem_wait(sem);
    printf("please input:\n");
    scanf("%s", buf);
    sem_post(sem + 1);
    if (!strcmp(buf, "bye"))
      break;
  }

  pthread_join(tid, NULL);

  sem_destroy(sem);
  sem_destroy(sem + 1);
  pthread_exit(NULL);
}

void *func(void *argv) {

  while (1) {
    sem_wait(sem + 1);
    printf("read is %s\n", buf);
    sem_post(sem);
    if (!strcmp(buf, "bye"))
      break;
  }

  pthread_exit(NULL);
}
